package com.terry.web.config.filter;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.val;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

/**
 * Date：2021/9/9
 * Time：21:16
 * Description：TODO
 *
 * @author Terry
 * @version 1.0
 */
@RequiredArgsConstructor
public class RestAuthenticationFilter  extends UsernamePasswordAuthenticationFilter {

    private final ObjectMapper objectMapper;


    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        UsernamePasswordAuthenticationToken authRequest;

        try {
            InputStream inputStream = request.getInputStream();
            val jsonNode  = objectMapper.readTree(inputStream);
            String userName = jsonNode.get("username").textValue();
            String password = jsonNode.get("password").textValue();
            authRequest = new UsernamePasswordAuthenticationToken(userName,password);


        } catch (IOException e) {
            e.printStackTrace();
            throw new BadCredentialsException("没有找到用户名或密码");
        }

        setDetails(request,authRequest);

        return this.getAuthenticationManager().authenticate(authRequest);
    }
}
